from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from django.utils import timezone


class UserProfile(models.Model):
    """用户完整信息 - 与Django认证系统完全集成"""
    
    GENDER_CHOICES = [
        ('male', '男'),
        ('female', '女'),
        ('other', '其他'),
        ('prefer_not_to_say', '不愿透露'),
    ]
    
    user = models.OneToOneField(
        User, 
        on_delete=models.CASCADE,
        verbose_name='关联用户',
        db_comment='关联用户',
        related_name='profile',  # 通过user.profile访问
        primary_key=True  # 保持user作为主键
    )
    
    # 用户展示字段（按要求顺序）
    avatar = models.URLField(
        max_length=500,
        null=True, 
        blank=True, 
        verbose_name='头像URL',
        db_comment='腾讯云COS头像URL'
    )
    
    # 用户名和邮箱直接使用User模型的字段
    
    nickname = models.CharField(
        max_length=50, 
        null=True, 
        blank=True, 
        verbose_name='昵称',
        db_comment='用户昵称'
    )
    gender = models.CharField(
        max_length=20,
        null=True,
        blank=True,
        choices=GENDER_CHOICES,
        verbose_name='性别',
        db_comment='用户性别'
    )
    
    phone = models.CharField(
        max_length=20, 
        null=True, 
        blank=True, 
        verbose_name='电话',
        db_comment='用户电话'
    )
    
    # 邮箱直接使用User.email
    
    points = models.IntegerField(
        default=0, 
        verbose_name='积分',
        db_comment='用户积分'
    )
    
    bio = models.TextField(
        null=True, 
        blank=True, 
        verbose_name='个人简介',
        db_comment='用户个人简介'
    )

    # 位置相关字段（便于后台管理与业务展示）
    lat = models.FloatField(
        null=True,
        blank=True,
        verbose_name='纬度',
        db_comment='最后一次定位的纬度'
    )
    lng = models.FloatField(
        null=True,
        blank=True,
        verbose_name='经度',
        db_comment='最后一次定位的经度'
    )
    city = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        verbose_name='城市',
        db_comment='最后一次定位的城市'
    )
    province = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        verbose_name='省份',
        db_comment='最后一次定位的省份'
    )
    nation = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        verbose_name='国家',
        db_comment='最后一次定位的国家'
    )
    location_updated_at = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name='定位更新时间',
        db_comment='最后一次定位信息更新时间'
    )
    
    # 不包含触发行为、关联业务id等流水字段
    
    created_at = models.DateTimeField(
        default=timezone.now,
        verbose_name='创建时间',
        db_comment='创建时间'
    )
    
    updated_at = models.DateTimeField(
        auto_now=True, 
        verbose_name='更新时间',
        db_comment='更新时间'
    )

    class Meta:
        db_table = 'xiangsu_user_profiles'
        db_table_comment = '用户扩展信息表-与Django认证系统合并'
        verbose_name = '用户信息'
        verbose_name_plural = '用户信息'

    def __str__(self):
        return f'{self.user.username}的完整信息'
    
    def get_user_info(self):
        """返回完整的用户信息（按要求字段顺序）"""
        # 如果头像URL存在，返回HTML格式的图片标签
        if self.avatar:
            avatar_html = f'<img src="{self.avatar}" alt="用户头像" style="width: 100px; height: 100px; border-radius: 50%; object-fit: cover;">'
        else:
            avatar_html = '<div style="width: 100px; height: 100px; border-radius: 50%; background: #f0f0f0; display: flex; align-items: center; justify-content: center; color: #999;">暂无头像</div>'
        
        return {
            'avatar': avatar_html,  # 直接返回HTML格式的图片
            'avatar_url': self.avatar,  # 保留原始URL，供需要时使用
            'username': self.user.username,
            'nickname': self.nickname,
            'phone': self.phone,
            'email': self.user.email,
            'points': self.points,
            'bio': self.bio,
            'lat': self.lat,
            'lng': self.lng,
            'city': self.city,
            'province': self.province,
            'nation': self.nation,
            'location_updated_at': self.location_updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.location_updated_at else None
        }


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    """信号：当创建User时自动创建UserProfile"""
    if created:
        UserProfile.objects.create(user=instance, created_at=timezone.now(), updated_at=timezone.now())


@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    """信号：当保存User时自动保存UserProfile"""
    try:
        instance.profile.save()
    except UserProfile.DoesNotExist:
        UserProfile.objects.create(user=instance, created_at=timezone.now(), updated_at=timezone.now())


# 轮播图模型移至社区模块


@receiver(pre_save, sender=UserProfile)
def mark_avatar_award(sender, instance, **kwargs):
    if instance.pk:
        try:
            old = UserProfile.objects.get(pk=instance.pk)
            if (not old.avatar) and instance.avatar:
                instance._should_award_avatar = True
        except UserProfile.DoesNotExist:
            pass


@receiver(post_save, sender=UserProfile)
def award_avatar_points(sender, instance, created, **kwargs):
    if getattr(instance, '_should_award_avatar', False):
        try:
            from rewards.utils import award_points
            award_points(instance.user, 1, 'avatar_upload', None)
        except Exception:
            pass
